<template>
  <!-- 显示商品的三方ID -->
  <el-dialog :title="'对接详情'" :visible.sync="dialogVisible" @close="close" :close-on-click-modal="false" append-to-body width="1260px">
    <div style="padding-bottom: 60px;" v-loading="loading">
      <div style="color: #999;margin-bottom: 10px;">
        提示：上下架会同步三方平台，可能会有延迟，请不要频繁进行上下架操作！
      </div>
      <el-form class="search-form-new" :model="queryParams" ref="queryFormQudaoGoods" :inline="true" label-width="68px">
        <!-- <el-form-item label="渠道类型" prop="channelType">
          <el-select clearable filterable v-model="queryParams.inter" placeholder="请选择渠道类型">
            <el-option :label="'接口'" :value="1" />
            <el-option :label="'脚本'" :value="2" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="渠道" prop="config">
          <el-select filterable v-model="queryParams.config" placeholder="请选择渠道" @change="qudaoChange">
            <el-option v-for="dict in saleList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工" prop="createId">
          <el-select clearable filterable v-model="queryParams.createId" placeholder="请选择员工">
            <el-option v-for="(item ,key) in yuangongList" :key="key" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品编号" prop="goodsId">
          <el-input v-model="queryParams.goodsId" placeholder="请输入商品编号" clearable />
        </el-form-item>
        <el-form-item label="游戏账号" prop="accountNumber">
          <el-input v-model="queryParams.accountNumber" placeholder="请输入游戏账号" clearable />
        </el-form-item>
        <el-form-item label="游戏" prop="gameId">
          <el-select filterable v-model="queryParams.gameId" placeholder="请选择游戏" clearable>
            <el-option v-for="dict in allGameList" :key="dict.id" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="duijieType" v-if="!this.type||this.type!='yiduijie'">
          <el-select clearable filterable v-model="queryParams.duijieType" placeholder="请选择状态">
            <el-option v-for="dict in sucessList" :key="dict.id" :label="dict.status" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="">
        <el-date-picker clearable v-model="timeArea" value-format="yyyy-MM-dd" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <!-- <el-button v-hasPermi="['add:price:remove']" type="danger" plain icon="el-icon-delete" :loading="exportLoading" @click="rmRec">一键重推</el-button> -->
        </el-form-item>
      </el-form>
      <el-table border stripe :data="list">
        <el-table-column prop="interfaceUserName" label="渠道名称">
          <template>
            <span>{{ currentQudao.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="channelType" label="类型" width="80">
          <template>
            <el-tag v-if="currentQudao.channelType==1">接口</el-tag>
            <el-tag type="warning" v-if="currentQudao.channelType==2">脚本</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gameName" label="游戏" width="100"></el-table-column>
        <el-table-column prop="goodsId" label="商品编号" width="80"></el-table-column>
        <el-table-column prop="accountNumber" label="游戏账号" width="100"></el-table-column>

        <el-table-column prop="outid" label="对接状态" width="80">
          <template slot-scope="scope">
            {{scope.row.outid?'已对接':'未对接'}}
          </template>
        </el-table-column>
        <el-table-column prop="outid" label="三方编号"></el-table-column>
        <el-table-column prop="tuisongjia" label="三方价格" width="100"> </el-table-column>
        <el-table-column prop="artCreateTime" label="对接时间" width="160"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.infoUrl&&scope.row.outid" type="warning" @click="viewPage(scope.row)">查看</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.outid&&!currentQudao.saleName.includes('JIAOYIMAO')" :loading="xiajiaLoading==scope.row.goodsId" @click="caozuoFn(scope.row,'del')">下架</el-button>
            <el-button size="mini" type="primary" v-if="!scope.row.outid&&!currentQudao.saleName.includes('JIAOYIMAO')" :loading="xiajiaLoading==scope.row.goodsId" @click="caozuoFn(scope.row,'add')">上架</el-button>
            <el-button size="mini" type="warning" plain @click="openLogDialog(scope.row)">推送记录</el-button>
            <el-button size="mini" type="danger" v-if="scope.row.artRec"  @click="delGoods(scope.row)">改为未对接</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :autoScroll="false" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>
    <div class="bot-box">
      <el-button plain @click="close" :loading="btnloading">关闭</el-button>
    </div>
    <!-- <div class="bot-box">
      <el-button type="primary" @click="yijian('add')" :loading="btnloading">一键上架</el-button>
      <el-button type="danger" @click="yijian('del')" :loading="btnloading">一键下架</el-button>
    </div> -->

    <showLogs ref="showLogs"></showLogs>
  </el-dialog>
</template>

<script>
import goodsListApi from "@/api/gameConfig/goodsList";
import showLogs from "../../tenantPages/goodsList/showLogs.vue";
import { allList } from "@/api/partner/partner";
import supplyConfigApi from "@/api/system/supplyConfig";
export default {
  name: "",
  components: { showLogs },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      btnloading: false,
      xiajiaLoading: null,
      shangjiaLoading: false,
      list: [],
      id: "",
      viewUrlMap: {
        JYM: "",
      },
      timer: null,
      goodsInfo: {},

      saleList: [],
      sucessList: [
        { status: "已对接", id: 1 },
        { status: "未对接", id: 2 },
      ],
      queryParams: {
        config: "",
        goodsId: "",
        createId: "",
        gameId: "",
        accountNumber: "",
        pageNum: 1,
        pageSize: 10,
        artCreateTimeStart:'',
        artCreateTimeEnd:'',
        duijieType:''
      },
      currentQudao: {},
      initQudao:{},
      total: 0,
      yuangongList: [],
      timeArea:[],
      type:''
    };
  },
  computed: {
    allGameList() {
      return this.$store.getters.allGameList;
    },
  },
  created() {},
  methods: {
    open(qudao,flag) {
      this.type = flag||''
      this.initQudao = JSON.parse(JSON.stringify(qudao))
      this.currentQudao = { ...qudao };
      console.log("%c Line:158 🍖 this.currentQudao", "color:#7f2b82", this.currentQudao);
      this.queryParams.config = qudao.id;
      this.getList();
      this.allSale();
      this.getYuangongList();
      this.dialogVisible = true;
      this.xiajiaLoading = null;
      this.btnloading = false;
    },
    // 获取所有渠道
    allSale() {
      allList({
        // channelType: 1,
      }).then((res) => {
        if (res.code == 200) {
          this.saleList = res.rows;
        }
      });
    },
    qudaoChange(e) {
      if (e) {
        this.saleList.forEach((r) => {
          if (r.id == e) {
            this.currentQudao = { ...r };
          }
        });
      }
    },
    // 获取所有员工列表
    getYuangongList() {
      supplyConfigApi
        .getAllUserList({
          userNewType: 1,
        })
        .then((res) => {
          this.yuangongList = res.rows;
        });
    },
    // 跳转三方页面
    viewPage(row) {
      let url = row.infoUrl;
      if (url) {
        if (row.infoUrl.includes("xxx") && row.artRec && row.artRec.outid) {
          url = row.infoUrl.replace(/xxx/g, row.artRec.outid);
        }
        window.open(url);
      }
    },
    // 获取商品列表
    getList() {
      // console.log("%c Line:36 🍎 res", "color:#2eafb0", 111);
      if (this.timeArea && this.timeArea.length) {
        this.queryParams.artCreateTimeStart = this.timeArea[0];
        this.queryParams.artCreateTimeEnd = this.timeArea[1] + " " + "23:59:59";
      } else {
        this.queryParams.artCreateTimeStart = "";
        this.queryParams.artCreateTimeEnd = "";
      }
      this.loading = true
      if(this.type=='yiduijie'){
        goodsListApi.partnerGetGoodsYituisong(this.queryParams).then((res) => {
          // console.log("%c Line:36 🍎 res", "color:#2eafb0", res);
          this.loading = false
          this.list = res.rows;
          this.total = res.total;
        }).catch(err=>{
          this.loading = false
        })
      }else{
        goodsListApi.partnerGetGoods(this.queryParams).then((res) => {
          // console.log("%c Line:36 🍎 res", "color:#2eafb0", res);
          this.loading = false
          this.list = res.rows;
          this.total = res.total;
        }).catch(err=>{
          this.loading = false
        })
      }
      
    },

    // 推送记录  打开
    openLogDialog(row) {
      this.$refs.showLogs.open(row.goodsId, this.currentQudao.saleName, this.currentQudao.channelType);
    },
    // // 一键上下架
    // yijian(type) {
    //   let ids = [];
    //   if (this.list && this.list.length) {
    //     if (type == "del") {
    //       this.list.forEach((r) => {
    //         if (r.artRec) {
    //           ids.push(r.id);
    //         }
    //       });
    //     } else if (type == "add") {
    //       this.list.forEach((r) => {
    //         if (!r.artRec) {
    //           ids.push(r.id);
    //         }
    //       });
    //     }
    //   } else {
    //     return this.$message.error("暂无对接渠道！");
    //   }
    //   if (ids.length == 0) {
    //     return this.$message.error(
    //       `没有可以${type == "del" ? "下架" : "上架"}的渠道！`
    //     );
    //   }
    //   this.$confirm(
    //     `该操作会将所有对接渠道${type == "del" ? "下架" : "上架"}，是否继续？`,
    //     "提示",
    //     {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning",
    //     }
    //   )
    //     .then(() => {
    //       this.btnloading = true;
    //       const obj = {
    //         id: this.id,
    //         configIds: ids.join(","),
    //         type,
    //       };
    //       // this.startInterval();
    //       goodsListApi.yijianByGoods(obj).then((res) => {
    //         this.btnloading = false;
    //         this.getList();
    //         // if (this.timer) clearInterval(this.timer);
    //         if (res.code == 200) {
    //           this.$message.success(
    //             "请求已提交，请以推送结果为准！可在推送记录查看详情。"
    //           );
    //         }
    //       });
    //     })
    //     .catch(() => {
    //       // if (this.timer) clearInterval(this.timer);
    //     });
    // },
     // 删除
     delGoods(row){
      this.$confirm(
        `该操作 <span style="color:red">不会同步</span> 三方渠道，只将本系统的对接状态改为未对接，<span style="color:red">操作前请务必确认三方渠道已下架或删除</span> 该商品，是否继续？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          dangerouslyUseHTMLString: true
        }
      ).then(async ()=>{
        try {
         const res = await goodsListApi.delOnePlat({
          goodsId:row.goodsId,
          config:this.currentQudao.id,
          interfaceUserName:this.currentQudao.interfaceUserName
         })
         if(res.code==200){
          this.$message.success('操作成功！');
         }
        } catch (error) {
          
        }
      })
    },
    // 下架 上架等
    caozuoFn(row, type) {
      const obj = {
        id: row.goodsId,
        config: this.currentQudao.id,
        type,
      };
      this.xiajiaLoading = row.goodsId;
      goodsListApi
        .pushApiByGoods(obj)
        .then((res) => {
          this.getList();
          this.xiajiaLoading = null;
          if (res.code == 200) {
            this.$message.success(
              "请求已提交，请以推送结果为准！可在推送记录查看详情。"
            );
          }
        })
        .catch((err) => {
          this.xiajiaLoading = null;
        });
    },
    // 轮询列表
    // startInterval() {
    //   if (this.timer) clearInterval(this.timer);
    //   this.timer = setInterval(() => {
    //     this.getList();
    //   }, 3000);
    // },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.timeArea = []
      this.resetForm("queryFormQudaoGoods");
      this.currentQudao = JSON.parse(JSON.stringify(this.initQudao))
      this.queryParams.config = this.currentQudao.id
      this.handleQuery();
    },
    close() {
      this.resetForm("queryFormQudaoGoods");
      this.timeArea = []
      // if (this.timer) clearInterval(this.timer);
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.top {
  height: 40px;
  background: #f3f3f3;
  align-items: center;
  padding: 0 15px;
  border-radius: 8px 8px 0 0;
  > span {
    margin-right: 20px;
    .val {
      color: #000;
    }
  }
}
.bot-box {
  width: 100%;
  height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  background-color: #fff;
  border-top: 1px solid #ccc;
  padding-top: 15px;
  z-index: 9;
  text-align: center;
}
</style>
